<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>信息流管理</el-breadcrumb-item>
      <el-breadcrumb-item>客户对账</el-breadcrumb-item>
    </el-breadcrumb>

    <Container class="u-mb15">
      <!-- 筛选 -->
      <el-form
        inline
        class="m-form--filter"
      >
        <el-form-item>
          <el-date-picker
            class="u-w330"
            size="mini"
            v-model="dateValue"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="dateChange"
            :clearable="false"
            format="yyyy/MM/dd"
            :picker-options="$store.state.PICKER_OPTIONS"
          >
          </el-date-picker> 
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择数据状态"
            v-model="filter.status"
          >
            <el-option
              v-for="item in STATEDATA"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <br/>
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择客户名称"
            v-model="filter.customerId"
            @change="handleChangeCustomerOptions"
          >
            <el-option
              v-for="item in customerOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择产品"
            v-model="filter.productId"
            @change="handleChangeProductOptions"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择平台"
            v-model="filter.platformId"
            @change="handleChangePlatformOptions"
          >
            <el-option
              v-for="item in platformOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w200"
            size="mini"
            filterable
            multiple
            collapse-tags
            placeholder="请选择账号ID"
            v-model="filter.usernameId"
            autocomplete="on"
          >
            <el-option
              v-for="(item, index) in usernameOptions"
              :key="index"
              :label="`${item.name}${item.accountName ? `(${item.accountName}`: ''}${item.id ? `,${item.id})` : ''}`"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择商务负责人"
            v-model="filter.businessId"
          >
            <el-option
              v-for="item in [{name: '全部商务', id: null}].concat(businessOptions)"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            size="mini"
            @click="search"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </Container>

    <Container>
      <!-- 表格操作 -->
      <el-form
        :model="ruleForm" :rules="rules" ref="ruleForm"
        inline
        class="m-table--handle"
      >
        <el-form-item>
          <el-button 
          size="mini" 
          type="primary" 
          @click="submitForm('ruleForm',1)"
          >按消耗结算</el-button>
        </el-form-item>
        <el-form-item>
           <el-button
            size="mini"
            type="primary"
            @click="submitForm('ruleForm',2)"
          >按充值结算</el-button>
        </el-form-item>
        <el-form-item>
           <el-button
            size="mini"
            type="primary"
            @click="submitForm('ruleForm',3)"
          >按服务费结算</el-button>
        </el-form-item>
        <el-form-item>
           <el-button
            size="mini"
            @click="submitForm('ruleForm',4)"
          >不予结算</el-button>
        </el-form-item>
        <p>请选择结算主体及结算数据</p>
        <el-form-item prop="myAccount">
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择我方结算主体"
            v-model="ruleForm.myAccount"
          >
            <el-option
              v-for="item in MYACCOUNT"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="customerIntroduct">
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="选择客户简称"
            v-model="ruleForm.customerIntroduct"
            @change="handleCustomerIntroduct"
          >
            <el-option
              v-for="item in customerIntroductOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="customerAccount">
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择客户结算主体"
            v-model="ruleForm.customerAccount"
          >
            <el-option
              v-for="item in customerAccountOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <CustomTableColumn :columns.sync="tableColumn" />
      </el-form>
      <!-- 表格 -->
      <el-table
        border
        stripe
        :data="tableData"
        @selection-change="changeTableSelection"
      >
        <el-table-column
          type="selection"
          width="35"
          fixed
          :selectable="handleSelectable"
        >
        </el-table-column>
        <el-table-column
          align="center"
          v-for="(item, index) in filterTableColumn"
          :label="item.label"
          :key="index"
        >
          <el-table-column
            :resizable="false"
            align="center"
            :label="item.prop === 'reportTime' ? '总计' : getTableDataSumValue(item.prop, {rate: []})"
            :prop="item.prop"
            class-name="u-table--total"
            :width="item.prop === 'reportTime' && 110"
          >
            <template slot-scope="scope">
               <!-- 账号名称 -->
              <template v-if="item.prop === 'accountName'">{{scope.row.accountName == '' || scope.row.accountName == null ? '-' : scope.row.accountName}}</template>
              <!-- 服务费率 -->
              <template v-else-if="item.prop === 'serviceRate'">{{scope.row.serviceRate + '%'}}</template>
              <!-- 当前返点 -->
              <template v-else-if="item.prop === 'rebates'">{{scope.row.rebates + '%'}}</template>
              <!-- 是否启用 -->
              <template v-else-if="item.prop === 'status'">{{scope.row.status === 1 ? "未生成结算单" : "已生成结算单"}} </template>
              <!-- 其他 -->
              <template v-else>{{scope.row[item.prop]}}</template>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        background
        :page-sizes="[50, 100, 500, 1000]"
        :page-size="page.pageSize"
        layout="total, prev, pager, next, sizes"
        :total="pageTotal"
        @size-change="handlePagerSizeChange"
        @current-change="handlePagerCurrentChange"
      />
    </Container>
  <el-dialog
    class="dialog"
    :title="settle.settleWay == 4?'不予结算':'生成对账单'"
    :visible.sync="dialogVisible"
    width="460px"
    >
    <!-- 按消耗结算 -->
    <div v-show="settle.settleWay == 1" >
      <el-form :model="settle" label-width="150px" >
        <el-form-item label="折后总消耗金额(元)">
          <el-input v-model="settle.discountedAmount" disabled></el-input>
        </el-form-item>
        <el-form-item label="核减金额(元)" prop="contractAmount">
          <el-input v-model.trim="settle.subtractAmount" @keyup.native="settle.subtractAmount = oninput(settle.subtractAmount)" type="number"></el-input>
        </el-form-item>
        <el-form-item label="实际总结算金额(元)">
          <el-input v-model="settlementAmount" disabled></el-input>
        </el-form-item>
      </el-form>
    </div>
    <!-- 按充值结算 -->
    <div v-show="settle.settleWay == 2" >
       <el-form :model="settle" label-width="150px">
        <el-form-item label="实际总结算金额(元)">
          <el-input v-model="settle.rechargeMoney" @keyup.native="settle.rechargeMoney = oninput(settle.rechargeMoney)" type="number"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <!-- 服务费率 -->
    <div v-show="settle.settleWay == 3" >
      <el-form :model="settle">
        <el-form-item label="实际总结算金额(元)" label-width="150px">
          <el-input v-model="settle.serveAmount" autocomplete="off" disabled></el-input>
        </el-form-item>
      </el-form>
    </div>
    <!-- 不予结算 -->
    <div v-show="settle.settleWay == 4">
      结算金额为 <span style="color:#04c1fe"> 0 </span> 元
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">关 闭</el-button>
      <el-button type="primary" @click="addSettle">{{settle.settleWay == 4?'确定不予结算':'对账无误，生成对账单'}}</el-button>
    </span>
  </el-dialog>
  </div>
</template>

<script>
import Container from "@/components/container";
import CustomTableColumn from "@/components/custom-table-column";

import { MYACCOUNT,STATEDATA,OPERATOR_OPTION, CUSTOMER_ROLE_OPTION } from "@/assets/js/flow-option";
import { mapOptionLabel } from "@/util";

export default {
  name: "flow-customer-reconciliation",
  components: {
    Container,
    CustomTableColumn
  },
  data() {
    return {
      OPERATOR_OPTION,
      MYACCOUNT,
      STATEDATA,
      CUSTOMER_ROLE_OPTION,
      BASE_URL: process.env.VUE_APP_BASE_URL,
      // 下拉
      businessTypeModel: "",
      dateValue:Number(this.$route.query.dataValue)|| null,
      customerOptions: [],
      productOptions: [],
      platformOptions: [],
      usernameOptions: [],
      businessOptions: [],
      // 表单下拉
      customerIntroductOptions:[],
      customerAccountOptions:[],
      ruleForm:{
        myAccount: Number(this.$route.query.myAccount) || null,
        customerIntroduct: Number(this.$route.query.customerIntroduct) || null,
        customerAccount: Number(this.$route.query.customerAccount) || null,
      },
      // 校验
      rules: {
        myAccount: [
          { required: true, message: '请选择我方结算主体', trigger: 'change' }
        ],
        customerIntroduct: [
          { required: true, message: '请选择客户简称', trigger: 'change' }
        ],
        customerAccount: [
          { required: true, message: '请选择客户结算主体', trigger: 'change' }
        ],
        
      },
      // 筛选
      filter: {
        startDate:'',
        endDate:'',
        businessId:Number(this.$route.query.businessId) || null,
        status: Number(this.$route.query.status) || 1,
        customerId: Number(this.$route.query.customerId) || null,
        productId: Number(this.$route.query.productId) || null,
        platformId: Number(this.$route.query.platformId) || null,
        usernameId: [null],
        operator: null
      },
      //弹出框结算数据
      settle:{
        discountedAmount:null, 
        settleWay:null, // 结算方式
        subtractAmount:0,
        settlementAmount:null,
        rechargeMoney:0,
        serveAmount:0,
      },
      dialogVisible:false, // 结算弹出框
      formLabelWidth: '120px',
      tableData: [],
      tableSelectionData: [],
      tableColumn: [
        {
          label: "日期（天）",
          prop: "reportTime",
          visible: true
        },
        {
          label: "客户名称",
          prop: "customerName",
          visible: true
        },
        {
          label: "产品名称",
          prop: "productName",
          visible: true
        },
        {
          label: "平台名称",
          prop: "platformName",
          visible: true
        },
        {
          label: "登陆账号",
          prop: "username",
          visible: true
        },
        {
          label: "账号名称",
          prop: "accountName",
          visible: true
        },
        {
          label: "账号ID",
          prop: "usernameId",
          visible: true
        },
        {
          label: "当日返点",
          prop: "rebates",
          visible: true
        },
        {
          label: "当日消耗（元）",
          prop: "consum",
          visible: true
        },
        {
          label: "激励消耗（元）",
          prop: "incentiveConsum",
          visible: true
        },
        {
          label: "折后消耗（元）",
          prop: "afterDiscountConsum",
          visible: true
        },
        {
          label: "服务费率",
          prop: "serviceRate",
          visible: true
        },
        {
          label: "商务负责人",
          prop: "business",
          visible: true
        },
        {
          label: "数据状态",
          prop: "status",
          visible: true
        }
      ],
      page: {
        pageNo: 1,
        pageSize: 50
      },
      pageTotal: 0
    };
  },
  computed: {
   settlementAmount(){
    return  (this.settle.discountedAmount*100000-this.settle.subtractAmount*100000)/100000
   },
    filterTableColumn() {
      return this.tableColumn.filter(item => item.visible);
    },
  },
  methods: {
    oninput(num) {
      num = num.match(/^\d*(\.?\d{0,5})/g)[0];
      return num
    },
    submitForm(formName,settleWay) {
      // 请选择数据
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 判断同一个商务负责人；
          this.settle.settleWay = settleWay;
          this.sameBusiness(
             this.tableSelectionData.map(item => item.id).join(),
             settleWay
          )
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    sameBusiness(id) {
      // let id = id
      if (!this.tableSelectionData.length) {
        return this.$message.warning("请选择需要操作的选项！");
      }
      this.$http({
        method: "post",
        url: "/manage/api/bus/customer_check/check_business",
        params: {
          ids:id
        }
      }).then(res => {
        if (res.data.code === 0) {
          //弹出框
          this.dialogVisible = true;
            if(this.settle.settleWay == 1){
              this.consumsettleData(id)
              
            }else if(this.settle.settleWay == 3) {
              this.serveSettleData(id)
            }else{
              this.settle.discountedAmount =0
            }
        }else{
          this.$message.warning(res.data.msg);
        }
      });
    },
    serveSettleData(id){
      this.$http({
        method: "post",
        url: "/manage/api/bus/customer_check/get_consume_service_rate",
        params: {
          ids:id
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.settle.serveAmount  = res.data.data.consum
        }
      });
    },
    consumsettleData(id){
      this.$http({
        method: "post",
        url: "/manage/api/bus/customer_check/get_consume",
        params: {
          ids:id
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.settle.discountedAmount  = res.data.data.consum
        }
      });
    },
    addSettle(){
      let allMoney = null;
      if(this.settle.settleWay == 1){
        allMoney = this.settlementAmount
      }else if(this.settle.settleWay == 2){
        allMoney = this.settle.rechargeMoney
      }else if(this.settle.settleWay == 3){
        allMoney = this.settle.serveAmount
      }else if(this.settle.settleWay == 4){
        allMoney = 0
      }
      this.dialogVisible = false
      let  params= {
          customerAptitudeId:this.ruleForm.customerAccount,
          customerId:this.ruleForm.customerIntroduct,
          discountedAmount:this.settle.discountedAmount,
          ids:this.tableSelectionData.map(item => item.id).join(),
          ourMain:this.ruleForm.myAccount,
          settleWay:this.settle.settleWay,
          settlementAmount:allMoney,
          subtractAmount:this.settle.settleWay == 1 ? this.settle.subtractAmount : 0,
        }
      this.$http({
        method: "post",
        url: "/manage/api/bus/customer_check/consume",
        data: {
         ...params
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.getTable()
        }
      });
    },
    dateChange() {
      this.filter.startDate = this.formatDateTime(this.dateValue[0], "y-m-d");
      this.filter.endDate = this.formatDateTime(this.dateValue[1], "y-m-d");
    },
    mapOptionLabel,

    // 下拉
    fetchCustomerOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/customer/get_customer_name",
        params: {
          status: 0
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.customerOptions = [
            {
              id: null,
              name: "全部客户"
            }
          ].concat(res.data.data);
          if (this.$route.query.customerId) {
            this.filter.customerId = Number(this.$route.query.customerId);
          }
        }
      });
    },
    fetchProductOptions(customerId = 0) {
      this.$http({
        method: "get",
        url: "/manage/api/bus/product/get_no_stop_product",
        params: { platformId:0,customerId: Number(customerId) }
      }).then(res => {
        if (res.data.code === 0) {
          this.productOptions = [
            {
              id: null,
              name: "全部产品"
            }
          ].concat(res.data.data);
          if (this.$route.query.productId) {
            this.filter.productId = Number(this.$route.query.productId);
          }
        }
      });
    },
    fetchPlatformOptions(customerId = 0, productId = 0) {
      this.$http({
        method: "get",
        url: "/manage/api/bus/platform/get_platform",
        params: {
          status: 0,
          customerId: Number(customerId),
          productId: Number(productId)
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.platformOptions = [
            {
              id: null,
              name: "全部平台"
            }
          ].concat(res.data.data);
          if (this.$route.query.platformId) {
            this.filter.platformId = Number(this.$route.query.platformId);
          }
        }
      });
    },
    fetchUsernameOptions(customerId = 0, productId = 0, platformId = 0) {
      this.$http({
        method: "get",
        url: "/manage/api/bus/account/get_username_id_list",
        params: {
          customerId: Number(customerId),
          productId: Number(productId),
          platformId: Number(platformId)
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.usernameOptions = [
            {
              id: null,
              name: "全部账号ID"
            }
          ].concat(res.data.data);
        }
      });
    },
    fetchBusinessOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/product/get_position",
        params: {
          position: 1
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.businessOptions = res.data.data;
        }
      });
    },
    fetchcustomerIntroductOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/customer/get_customer_name",
        params: {
          status: 0
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.customerIntroductOptions =  [
            {
              id: null,
              name: "请选择客户简称"
            }
          ].concat(res.data.data)
        }
      });
    },
    fetchcustomerAccountOptions(id) {
      this.$http({
        method: "get",
        url: "/manage/api/bus/customer_check/get_customer",
        params: {
          customerId: id
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.customerAccountOptions = res.data.data;
        }
      });
    },
    handleChangeCustomerOptions() {
      this.filter.productId = null;
      this.filter.platformId = null;
      this.filter.usernameId = [null];
      this.fetchProductOptions(this.filter.customerId);
    },
    handleChangeProductOptions() {
      this.filter.platformId = null;
      this.filter.usernameId = [null];
      this.fetchPlatformOptions(this.filter.customerId, this.filter.productId);
    },
    handleChangePlatformOptions() {
      this.filter.usernameId = [null];
      this.fetchUsernameOptions(this.filter.customerId, this.filter.productId, this.filter.platformId);
    },
    handleCustomerIntroduct(id){
      this.ruleForm.customerAccount = null
      this.fetchcustomerAccountOptions(id)
    },
    // addOperate() {
    //   this.dialogOperateData.operate.push({ operatorBy: "", startDate: "" });
    // },
    // removeOperate(index) {
    //   this.dialogOperateData.operate.splice(index, 1);
    // },
    // 列表
    search() {
      this.page.pageNo = 1;
      this.getTable();
    },
    //获取列表
    getTable() {
      this.$http({
        method: "post",
        url: "/manage/api/bus/account_data/get_list",
        data: {
          ...this.filter,
          ...this.page,
          usernameId: this.filter.usernameId.includes(null)
            ? null
            : this.filter.usernameId.join()
        }
      }).then(res => {
        if (res.data.code === 0) {
          let data = res.data.data;
          if(data.list.length == 0){
            this.tableData = data.list
          }else{
            this.tableData = this.modTableDataSumList(
              data.sumList,
              data.list
            );
          }
          this.pageTotal = data.listCount;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    // 给第一行数据添加总计相关数据
    modTableDataSumList(sumList, data) {
      let sum = sumList.length ? sumList[0] : {};
      let sumObj = {};
      for (let key in sum) {
        sumObj[`__` + key] = sum[key];
      }
      data[0] = {
        ...data[0],
        ...sumObj
      };
      return data;
    },
    // 获取总计的相关值
    getTableDataSumValue(prop, { rate }) {
      let sum = this.tableData[0] || {};
      let sumProp = `__${prop}`;
      if (sumProp in sum) {
        let value = sum[sumProp];
        // 添加百分比
        if (rate.indexOf(prop) !== -1) {
          return value
        }
        return String(value);
      }
      return "";
    },
    //判断选择框是否可选
    handleSelectable(row) {
      return row.status == 1 ? true :false ;
    },
    changeTableSelection(data) {
      this.tableSelectionData = data;
    },
    handlePagerSizeChange(v) {
      this.page.pageSize = v;
      this.getTable();
    },
    handlePagerCurrentChange(v) {
      this.page.pageNo = v;
      this.getTable();
    }
  },
  activated(){
    this.getTable();
  },
  created() {
    this.fetchCustomerOptions();
    this.fetchProductOptions();
    this.fetchPlatformOptions();
    this.fetchUsernameOptions();
    this.fetchBusinessOptions();
    this.fetchcustomerIntroductOptions();
    // this.fetchcustomerAccountOptions();
    
  }
};
</script>